package cn.hj.domain.strategy.service.rule.chain.factory;

import cn.hj.domain.strategy.adapter.repository.IStrategyRepository;
import cn.hj.domain.strategy.model.entity.StrategyEntity;
import cn.hj.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 工厂
 */
@Service
public class DefaultChainFactory {

    private final Map<String, ILogicChain> logicChainGruop;

    private final IStrategyRepository strategyRepository;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainGruop,IStrategyRepository strategyRepository) {
        this.strategyRepository = strategyRepository;
        this.logicChainGruop = logicChainGruop;
    }

    public ILogicChain openChain(Long strategyId) {


        StrategyEntity strategyEntity = strategyRepository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategyEntity.ruleModels();
        if ( ruleModels == null || ruleModels.length == 0 ){
            return logicChainGruop.get("default");
        }

        //构造链
        ILogicChain logicChain = logicChainGruop.get(ruleModels[0]);
        ILogicChain current = logicChain;
        for (int i = 1; i < ruleModels.length; i++) {
            ILogicChain nextChain = logicChainGruop.get(ruleModels[i]);
            current = current.appendNext(nextChain);
        }

        //填充兜底链
        current.appendNext(logicChainGruop.get("default"));
        return logicChain;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_WIGHT("rule_weight", "【抽奖前规则】根据抽奖权重返回可抽奖范围KEY", "before"),
        RULE_BLACKLIST("rule_blacklist", "【抽奖前规则】黑名单规则过滤，命中黑名单则直接返回", "before"),
        RULE_LOCK("rule_lock", "【抽奖前规则】抽奖锁规则：当用户抽奖次数超过n次后，解锁", "center"),
        RULE_LOCK_AWARD("rule_lock_award", "【抽奖后规则】抽奖锁规则：幸运奖兜底", "after"),
        RULE_DEFAULT("default", "默认", "default");

        private final String code;
        private final String info;
        private final String type;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {

        /**
         * 抽奖奖品ID - 内部流转使用
         */
        private Integer awardId;

        /**
         * 抽奖类型；黑名单抽奖、权重规则、默认抽奖
         */
        private String logicModel;

        /**
         * 抽奖奖品规则
         */
        private String awardRuleValue;
    }
}
